package com.zhangxin.aiInterview.manager.work_flow.tec_interview_analyze;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhangxin.aiInterview.manager.work_flow.tec_interview_analyze.model.TecInterviewAnalysisResult;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TecInterviewAnalyze {
    public static void main(String[] args) throws Exception {
        System.out.println(analyzeTecInterview(1L, 1L));
    }

    /**
     * 分析技术面试结果
     *
     * @param userId
     * @param aiInterviewId
     * @return
     * @throws Exception
     */
    public static TecInterviewAnalysisResult analyzeTecInterview(Long userId, Long aiInterviewId) throws Exception {

        URL url = new URL("https://api.dify.ai/v1/workflows/run");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 必须设置的请求头
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer app-EPoi7hUsJpyLAsp016dbxE3q");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "text/event-stream");

        // 关键连接配置
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(0); // 启用分块传输
        conn.setReadTimeout(0); // 禁用读取超时

        // 发送请求体
        //todo 后期将数据库修改为线上数据库，因为这个操作是查询的线上数据库中的数据，线上数据库并没有本地数据库的这些数据
        String body = String.format(
                "{\"inputs\": {\"userId\": \"%s\", \"aiInterviewId\": \"%s\"}, \"response_mode\": \"streaming\", \"user\": \"abc-123\"}",
                userId, aiInterviewId
        );
        System.out.println("body: " + body);
        try (OutputStream os = conn.getOutputStream()) {
            os.write(body.getBytes(StandardCharsets.UTF_8));
        }

        // 处理流式响应
        String result = "";
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()))) {

            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过心跳包
                if ("event: ping".equals(line.trim())) {
                    continue;
                }

                // 只获取最后一部分的数据
                JSONObject jsonObject = extractOutputs(line);
                if (ObjUtil.isEmpty(jsonObject)) continue;
                assert jsonObject != null;
                result = jsonObject.toString();
                System.out.println(result);
                return parseTecInterviewAnalysis(result);
            }
        }
        return null;
    }

    /**
     * 提取 workflow_finished 事件中的 outputs 数据
     *
     * @param sseEvent 原始事件字符串（如 "data: {...}"）
     * @return 成功返回 JSONObject 格式的 outputs，失败返回 null
     */
    public static JSONObject extractOutputs(String sseEvent) {
        // 1. 校验并去除 "data: " 前缀
        if (!sseEvent.startsWith("data: ")) {
            return null;
        }
        String jsonStr = sseEvent.substring(6).trim();

        // 2. 解析为 JSONObject
        JSONObject event = JSONUtil.parseObj(jsonStr);
        if (event == null) {
            return null;
        }

        // 3. 校验事件类型
        if (!"workflow_finished".equals(event.getStr("event"))) {
            return null;
        }

        // 4. 提取 outputs
        JSONObject data = event.getJSONObject("data");
        if (data == null) {
            return null;
        }
        return data.getJSONObject("outputs");
    }

    /**
     * 从JSON数据中解析面试评估结果（使用Hutool）
     *
     * @param json 输入的原始JSON字符串
     * @return InterviewAnalysisResult 封装后的分析结果对象
     */
    public static TecInterviewAnalysisResult parseTecInterviewAnalysis(String json) {

        JSONObject root = JSONUtil.parseObj(json);

        TecInterviewAnalysisResult result = new TecInterviewAnalysisResult();

        // 解析 t-out1 - 沟通表达能力总结
        result.setCommunicationSummary(root.getJSONObject("t-out1").getStr("summary"));

        // 解析 t-out2 - 技术分析
        JSONObject out2 = root.getJSONObject("t-out2");
        result.setTechnicalSummary(out2.getStr("summary"));

        JSONArray technicalArr = out2.getJSONArray("questionList");
        List<TecInterviewAnalysisResult.TechnicalQuestion> technicalList = new ArrayList<>();
        //分数列表
        List<Double> scores = new ArrayList<>();
        for (int i = 0; i < technicalArr.size(); i++) {
            JSONObject item = technicalArr.getJSONObject(i);
            TecInterviewAnalysisResult.TechnicalQuestion tq = new TecInterviewAnalysisResult.TechnicalQuestion();
            tq.setQuestion(item.getStr("question"));
            tq.setUserAnswer(item.getStr("user_answer"));
            tq.setScore(item.getDouble("score"));
            tq.setRemark(item.getStr("remark"));
            tq.setSuggest(item.getStr("suggest"));
            technicalList.add(tq);
            scores.add(tq.getScore());
        }
        result.setTechnicalQuestions(technicalList);
        //记住当前题目的分数
        result.setScores(scores);

        // 解析 t-out3 - 多模态分析
        JSONObject out3 = root.getJSONObject("t-out3");
        result.setMultimodalSummary(out3.getStr("summary"));

        JSONArray multimodalArr = out3.getJSONArray("questionList");
        List<TecInterviewAnalysisResult.MultimodalQuestion> multimodalList = new ArrayList<>();
        for (int i = 0; i < multimodalArr.size(); i++) {
            JSONObject item = multimodalArr.getJSONObject(i);
            TecInterviewAnalysisResult.MultimodalQuestion mq = new TecInterviewAnalysisResult.MultimodalQuestion();

            mq.setMicroExpression(item.getStr("microExpression"));
            mq.setFacialActions(item.getStr("facialActions"));
            mq.setBodyMovements(item.getStr("bodyMovements"));
            mq.setAudioEmotion(item.getStr("audioEmotion"));

            // 注意：类中字段为 remark
            mq.setRemark(item.getStr("remark"));

            multimodalList.add(mq);
        }
        result.setMultimodalQuestions(multimodalList);

        return result;
    }


}
